<template>
  <div>
    <el-dialog v-model="deviceDialog.visible.value" :title="deviceDialog.title.value" width="1300px" append-to-body destroy-on-close>
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="90px">
          <el-form-item label="模型id" >
            <el-input v-model="queryParams.modelId" :disabled="prop.modelId != null" placeholder="请输入模型id" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="设备名称" >
            <el-input v-model="queryParams.thingName" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="() => resetQuery()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card shadow="hover" style="height: 500px; margin-top: 6px;">
        <template v-if="prop.multiple" #header>
          <el-tag v-for="device in selectDeviceList" :key="device.thing_id" closable style="margin: 2px" @close="handleCloseTag(device)">
            {{ device.thing_name }}
          </el-tag>
        </template>

        <vxe-table
          ref="tableRef"
          height="416px"
          border
          show-overflow
          :data="deviceList"
          :loading="deviceLoading || selectDeviceLoading"
          :row-config="{ keyField: 'thing_id', isHover: true }"
          :checkbox-config="{ checkMethod: ({ row }) => { return row.localDeviceId == null }, reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
          @checkbox-all="handleCheckboxAll"
          @checkbox-change="handleCheckboxChange" 
        >
          <vxe-column type="checkbox" width="50" align="center" />
          <vxe-column key="model_name" field="model_name" title="模型名称" align="center" min-width="120px" />
          <vxe-column key="model_id" field="model_id" title="模型id" align="center" min-width="120px" />
          <vxe-column key="thing_name" field="thing_name" title="设备名称" align="center" min-width="160px" />
          <vxe-column key="thing_id" field="thing_id" title="设备识别码" align="center" min-width="160px" />
          <vxe-column title="是否引用" align="center" min-width="80px" >
            <template #default="scope">
              {{ scope.row.localDeviceId ? '是' : '否' }}
            </template>
          </vxe-column>
        </vxe-table>

        <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="pageList" />
      </el-card>

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { UserVO } from '@/api/system/user/types';
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';
import request from '@/utils/request';

interface PropType {
  modelValue?: any;
  multiple?: boolean;
  data?: any;
  modelId?: any;
}
const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined,
  modelId: null
});
const emit = defineEmits(['update:modelValue', 'confirmCallBack']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const selectDeviceList = ref<any[]>([]);

const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<VxeTableInstance<UserVO>>();

const deviceDialog = useDialog({
  title: '设备选择'
});

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  thingName: null,
  modelId: prop.modelId
});

const confirm = () => {
  emit('update:modelValue', selectDeviceList.value);
  emit('confirmCallBack', selectDeviceList.value);
  deviceDialog.closeDialog();
};

const computedIdList = (data) => {
  if (data instanceof Array) {
    return [...data];
  } else if (typeof data === 'string') {
    return data.split(',');
  } else if (typeof data === 'number') {
    return [data];
  } 

  return [];
};

/** 查询设备列表 */
const deviceList = ref<any[]>();
const deviceLoading = ref(false);
const total = ref(0);
const getList = async () => {
  queryParams.value.modelId = prop.modelId;
  deviceLoading.value = true; 
  const res:any = await request({ url: '/equipment/equipment-info/get-iot-device-list', method: 'get', params: queryParams.value }).finally(() => { deviceLoading.value = false; })
  console.log('获取iot设备列表：', res);

  deviceList.value = res.things;
  total.value = res.count;
};

/**
 * 初始化已选设备
 */
const selectDeviceLoading = ref(false);
const defaultSelectDeviceIdList = computed(() => computedIdList(prop.data));
const initSelectDevice = async () => {
  if (defaultSelectDeviceIdList.value.length > 0) {
    selectDeviceLoading.value = true;
    const res = await request({ url: '/equipment/equipment-info/get-iot-device-list', method: 'get', params: { thingIdList: defaultSelectDeviceIdList.value }}).finally(() => { selectDeviceLoading.value = false; })
    console.log('初始化已选设备：', res);

    selectDeviceList.value = res.rows;
    const selectedDeviceList = deviceList.value.filter((item) => {
      return defaultSelectDeviceIdList.value.includes(String(item.thing_id));
    });

    // 选中已选设备
    await nextTick(() => {
      tableRef.value?.setCheckboxRow(selectedDeviceList, true);
    });
  }
};

const pageList = async () => {
  await getList();
  const selectedDeviceList = deviceList.value.filter((item) => {
    return selectDeviceList.value.some((user) => user.thing_id === item.thing_id);
  });
  await tableRef.value.setCheckboxRow(selectedDeviceList, true);
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = (refresh = true) => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.modelId = prop.modelId;
  refresh && handleQuery();
};

const handleCheckboxChange = (checked) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value.setCheckboxRow(selectDeviceList.value, false);
    selectDeviceList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectDeviceList.value.push(row);
  } else {
    selectDeviceList.value = selectDeviceList.value.filter((item) => {
      return item.thing_id !== row.thing_id;
    });
  }
};
const handleCheckboxAll = (checked) => {
  const rows = deviceList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectDeviceList.value.some((item) => item.thing_id === row.thing_id)) {
        selectDeviceList.value.push(row);
      }
    });
  } else {
    selectDeviceList.value = selectDeviceList.value.filter((item) => {
      return !rows.some((row) => row.thing_id === item.thing_id);
    });
  }
};

const handleCloseTag = (item: any) => {
  const thing_id = item.thing_id;
  // 使用split删除用户
  const index = selectDeviceList.value.findIndex((item) => item.thing_id === thing_id);
  const rows = selectDeviceList.value[index];
  tableRef.value?.setCheckboxRow(rows, false);
  selectDeviceList.value.splice(index, 1);
};

const close = () => {
  deviceDialog.closeDialog();
};

watch(
  () => deviceDialog.visible.value, async (newValue: boolean) => {
    if (newValue) {
      await getList(); // 初始化列表数据
      await initSelectDevice();
    } else {
      tableRef.value.clearCheckboxReserve();
      tableRef.value.clearCheckboxRow();
      resetQuery(false);
      selectDeviceList.value = [];
    }
  }
);

defineExpose({
  open: deviceDialog.openDialog,
  close: deviceDialog.closeDialog
});
</script>
<style lang="scss" scoped>
  :deep(.el-dialog) {
    height: 750px !important;
  }
</style>
